package com.shuwen.gcdj.controller;

import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.constant.MemberCst;
import com.shuwen.gcdj.common.enums.ErrorCode;
import com.shuwen.gcdj.dto.account.InitUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@EnableAspectJAutoProxy(exposeProxy = true)
public class AuthController {

    /**
     * 初始化已登录用户信息
     *
     * @param request HttpServletRequest
     * @return InitUserDto
     */
    public InitUserDto initUser(HttpServletRequest request) {
        try {
            InitUserDto initUserDto = (InitUserDto) request.getAttribute(Constants.CURRENT_USER_INFO_REQUEST_KEY);
            if (initUserDto == null) {
                return null;
            }
            log.info("AuthController.initUser() initUserDto = {}, ", initUserDto);
            return initUserDto;
        } catch (Exception e) {
            log.error("Error: AuthController.initUser() 转换初始化对象异常; error = {}", e.getMessage());
            throw new ApiException(ErrorCode.UNAUTHORIZED);
        }
    }

    /**
     * 获取页面权限码
     *
     * @param request HttpServletRequest
     * @return String
     */
    public String getPowerCode(HttpServletRequest request) {
        try {
            String powerCode = (String) request.getAttribute(MemberCst.HEADER_KEY_POWER_CODE);
            if (powerCode == null) {
                return null;
            }
            log.info("AuthController.getPowerCode() powerCode = {}, ", powerCode);
            return powerCode;
        } catch (Exception e) {
            log.error("Error: AuthController.getPowerCode() 获取页面权限码错误; error = {}", e.getMessage());
            throw new ApiException(ErrorCode.POWER_CODE_MISS_FROM_HEADER);
        }
    }

    /**
     * 获取页面Token
     *
     * @param request HttpServletRequest
     * @return String
     */
    public String getJwtToken(HttpServletRequest request) {
        try {
            String jwtToken = (String) request.getAttribute(MemberCst.JWT_TOKEN_HEADER_KEY);
            if (jwtToken == null) {
                return null;
            }
            log.info("AuthController.getJwtToken() jwtToken = {}, ", jwtToken);
            return jwtToken;
        } catch (Exception e) {
            log.error("Error: AuthController.getJwtToken() 获取页面获取页面Token错误; error = {}", e.getMessage());
            throw new ApiException(ErrorCode.JWT_TOKEN_MISS_FROM_HEADER);
        }
    }
}
